/* 
 * -------------------------------------------------------------------
 * This is music class for android that implements the music interface.
 * 2011, by Wu Mu Xian
 * -------------------------------------------------------------------
*/

package mygame.myandroidgameframework;

import java.io.IOException;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

import mygame.basicgameframework.Music;

public class MyAndroidMusic implements Music, OnCompletionListener{
	
	MediaPlayer mediaPlayer; // the android media player
	boolean isPrepared = false; // is the music prepared to play
	
	// the constructor, set up the streaming
	public MyAndroidMusic(AssetFileDescriptor assetDescriptor) {
		mediaPlayer = new MediaPlayer();
		try { 
            mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(), 
                    assetDescriptor.getStartOffset(), 
                    assetDescriptor.getLength()); 
            mediaPlayer.prepare(); 
            isPrepared = true; 
            mediaPlayer.setOnCompletionListener(this); 
        } catch (Exception e) { 
            throw new RuntimeException("Couldn't load music"); 
        }	
	}
	
	// play the music
	public void play() {
		if (mediaPlayer.isPlaying()) 
            return; 
 
        try { 
            synchronized (this) { 
                if (!isPrepared) 
                    mediaPlayer.prepare(); 
                mediaPlayer.start(); 
            } 
        } catch (IllegalStateException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }
	}

	// stop the music
	public void stop() {
		mediaPlayer.stop();
		synchronized(this) {
			isPrepared = false;
		}
	}

	// pause the music
	public void pause() {
		if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
	}

	// enable/disable looping
	public void setLooping(boolean looping) {
		mediaPlayer.setLooping(looping);	
	}

	// set the volume of the music
	public void setVolume(float volume) {
		mediaPlayer.setVolume(volume, volume);
	}

	// is the music being played
	public boolean isPlaying() {
		return mediaPlayer.isPlaying();
	}

	// is the music stopped
	public boolean isStoped() {
		return !isPrepared;
	}

	// is the music in loop mode
	public boolean isLooping() {
		return mediaPlayer.isLooping();
	}

	// dispose the music
	public void dispose() {
		if(mediaPlayer.isPlaying())
			mediaPlayer.stop();
		mediaPlayer.release();
	}

	// called when the end of a media source is reached during playback.
	public void onCompletion(MediaPlayer mp) {
		synchronized (this) { 
            isPrepared = false;
		}
	}
}
